<template>
  <div class="app-container-app">
    <div class="header">
      <el-form ref="queryFormRef" :inline="true" :model="queryParams">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="queryParams.keywords" placeholder="请输入(用户名/昵称/手机号)" style="width: 200px" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="用户状态" style="width: 150px" clearable>
            <el-option label="正常" :value="1" />
            <el-option label="停用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery" :loading="loading">查询</el-button>
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="footer">
      <div class="util">
        <el-button type="primary" v-hasPermi="['sys:user:add']" @click="handleAdd">
          <el-icon>
            <Plus />
          </el-icon>
          新增用户
        </el-button>
      </div>
      <div class="table-inner">
        <el-table v-loading="loading" :data="userList" style="width: 100%; height: 100%" border>
          <el-table-column prop="username" label="用户名" align="center" width="120" show-overflow-tooltip />
          <el-table-column prop="nickname" label="昵称" align="center" show-overflow-tooltip />
          <el-table-column prop="gender" label="性别" align="center" width="60">
            <template #default="scope">
              {{ scope.row.genderLabel }}
            </template>
          </el-table-column>
          <el-table-column prop="roleNames" label="关联角色" align="center" width="180" show-overflow-tooltip />
          <el-table-column prop="mobile" label="手机号" align="center" width="120" />
          <el-table-column prop="status" label="状态" align="center" width="100">
            <template #default="scope">
              <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" inline-prompt active-text="启用"
                inactive-text="停用" @change="handleStatusChange($event, scope.row)" />
            </template>
          </el-table-column>
          <el-table-column prop="deptName" label="部门" align="center" width="180" show-overflow-tooltip />
          <el-table-column prop="createTime" label="创建时间" align="center" width="180" show-overflow-tooltip />
          <el-table-column label="操作" width="240" align="center" fixed="right">
            <template #default="scope">
              <el-button type="primary" link icon="Edit" @click="handlePassword(scope.row)" v-hasPermi="['sys:user:password:edit']">密码重置</el-button>
              <el-button type="primary" link icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['sys:user:edit']">修改</el-button>
              <el-button type="danger" link icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['sys:user:delete']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination v-if="total > 0" v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize" :total="total" :page-sizes="[10, 20, 50, 100]" background
        layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
    <UserDialog ref="userDialogRef" @success="getList" />
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessageBox, ElMessage, FormInstance } from 'element-plus'
import { Search, Plus, Refresh } from '@element-plus/icons-vue'
import UserDialog from './userDialog.vue'
import { listUser, delUser, changeUserStatus, Userpassword } from '@/api/user'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  keywords: '',
  // mobile: '',
  status: undefined
})

// 遮罩层
const loading = ref(false)
// 总条数
const total = ref(0)
// 用户列表
const userList = ref([])
// 查询表单ref
const queryFormRef = ref<FormInstance>()
// 弹框ref
const userDialogRef = ref()

/** 查询用户列表 */
const getList = async () => {
  loading.value = true
  try {
    const res = await listUser(queryParams)
    userList.value = res.data.list
    total.value = res.data.total
  } catch (error: any) {
    ElMessage.error(error.msg || '查询失败')
  } finally {
    loading.value = false
  }
}

/** 查询按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.pageNum = 1
  queryParams.keywords = ''
  queryParams.status = undefined
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 新增按钮操作 */
const handleAdd = () => {
  userDialogRef.value.show()
}

/** 修改按钮操作 */
const handleUpdate = (row: any) => {
  userDialogRef.value.show(row)
}
/** 重置密码操作 */
const handlePassword = async (row: any) => {
  try {
    if (!row?.id) {
      ElMessage.error("用户ID不能为空");
      return;
    }

    const formData = new FormData();
    formData.append('userId', row.id);
    formData.append('password', 'dc@123456+');

    const response = await Userpassword(formData, row.id);

    // 验证成功与否
    if (response?.code === '00000') {
      ElMessage.success("密码重置成功");
    } else {
      // 当 response 不成功时，打印返回信息
      ElMessage.warning(response?.msg || "密码重置失败");
    }
  } catch (error: any) {
    // 更新这里以捕获不同类型的错误
    console.log(error);
    // 确保从 error 中获取合适的消息
    const errorMessage = error.response?.data?.msg || '密码重置失败';
    ElMessage.error(errorMessage);
  }
}
/** 删除按钮操作 */
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `是否确认删除用户"${row.username}"?`,
    "警告",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }
  )
    .then(async () => {
      try {
        await delUser(row.id)
        getList()
        ElMessage.success("删除成功")
      } catch (error: any) {
        ElMessage.error(error.msg || '删除失败')
      }
    })
    .catch(() => { })
}

/** 状态修改 */
const handleStatusChange = async (value: number, row: any) => {
  const text = value === 1 ? '启用' : '停用'
  try {
    await ElMessageBox.confirm(
      `确认要${text}用户"${row.username}"吗?`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    )

    const formData = new FormData()
    formData.append('userId', row.id)
    formData.append('status', value)

    await changeUserStatus(formData, row.id)
    ElMessage.success(`${text}成功`)
  } catch (error: any) {
    row.status = value === 1 ? 0 : 1
    if (error !== 'cancel') {
      ElMessage.error(error.msg || '修改失败')
    }
  }
}

/** 分页大小改变 */
const handleSizeChange = (val: number) => {
  queryParams.pageSize = val
  getList()
}

/** 页码改变 */
const handleCurrentChange = (val: number) => {
  queryParams.pageNum = val
  getList()
}

/** 初始化 */
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .header {
    display: flex;
    padding: 16px 16px 0px 16px;
    margin-bottom: 16px;
    border-radius: 4px;
    background: white;
    box-shadow: 0 0 12px rgb(0 0 0 / 5%);
  }

  .footer {
    flex: 1;
    display: flex;
    padding: 16px;
    flex-direction: column;
    border-radius: 4px;
    overflow: hidden;
    background: white;
    box-shadow: 0 0 12px rgb(0 0 0 / 5%);
    position: relative;
    box-sizing: border-box;
    gap: 16px;

    .util {
      margin-bottom: 15px;
      display: flex;
      justify-content: flex-end;
      flex-shrink: 0;
    }

    .table-inner {
      flex: 1;
      position: relative;
    }
  }

  :deep(.el-pagination) {
    justify-content: flex-end;
  }
}
</style>